//
//  HTMLHelper.m
//  ShowYork
//
//  Created by hxh on 2020/9/8.
//  Copyright © 2020 hxh. All rights reserved.
//

typedef void(^doneBlock)(NSMutableAttributedString *content);
#import "HTMLHelper.h"

@interface HTMLHelper ()
@property (nonatomic,copy)doneBlock done;
@end

@implementation HTMLHelper
- (void)attributedTextFromHTML:(NSString *)originHtml andCompleteBlock:(void (^)(NSMutableAttributedString * attr))completeBlock{
    if (completeBlock) {
        self.done = ^(NSMutableAttributedString *content) {
            completeBlock(content);
        };
    }
    [self attributedTextFromHTML:originHtml];
}

- (void)attributedTextFromHTML:(NSString *)html {
    
    if (html.length == 0 ) {
        return;
    }
    NSMutableString *mutableHtml = [html mutableCopy];
    NSMutableArray<NSString *> *subStrings = [[NSMutableArray alloc] init];
    NSMutableArray<NSString *> *imageurlArray = [[NSMutableArray alloc] init];
    NSMutableArray<NSString *> *ranges = [[NSMutableArray alloc] init];
    //标签匹配
    
 
    NSString *parten = @"<img(.*?)>";
    NSError* error = NULL;
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
    NSArray* match = [reg matchesInString:html options:0 range:NSMakeRange(0, [html length])];
    if (match.count > 0) {
        for (NSTextCheckingResult *result in match) {
            //过去数组中的标签
            NSRange range = [result range];
            NSString *rangeString = NSStringFromRange(range);
            [ranges addObject:rangeString];
            NSString * subString = [html substringWithRange:range];
            //从图片中的标签中提取ImageURL
            NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
            NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
            NSRegularExpression *subRegOne = [NSRegularExpression regularExpressionWithPattern:@"https://(.*?)\"" options:0 error:NULL];
            NSArray *matchOne = [subRegOne matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
            NSMutableArray *tmpItems = [[NSMutableArray alloc] init];
            if (match.count > 0) {
                [tmpItems addObjectsFromArray:match];
            }
            if (matchOne.count > 0) {
                [tmpItems addObjectsFromArray:matchOne];
            }
            if (tmpItems.count > 0) {
                NSTextCheckingResult * subRes = tmpItems[0];
                NSRange subRange = [subRes range];
                subRange.length = subRange.length -1;
                NSString * imagekUrl = [subString substringWithRange:subRange];

                //将提取出的图片URL添加到图片数组中
                [imageurlArray addObject:imagekUrl];
            }
        }
    }
    if (ranges.count > 0) {
        NSUInteger startIndex = html.length;
        NSUInteger length = 0;
        for (NSInteger index = ranges.count - 1; index >= 0; index--) {
            NSRange tmpRange = NSRangeFromString(ranges[index]);
            startIndex = tmpRange.location + tmpRange.length;
            length = mutableHtml.length - startIndex;
            if (startIndex < mutableHtml.length ) {
                NSRange subStringRange = NSMakeRange(startIndex, length);
                NSString *tmpString = [mutableHtml substringWithRange:subStringRange];
                if (subStrings.count == 0) {
                    [subStrings addObject:tmpString];
                } else {
                    [subStrings insertObject:tmpString atIndex:0];
                }
            }
            mutableHtml = [[mutableHtml substringToIndex:tmpRange.location] mutableCopy];
        }
        if (mutableHtml.length > 0) {
            if (subStrings.count == 0) {
                [subStrings addObject:mutableHtml];
            } else {
                [subStrings insertObject:mutableHtml atIndex:0];
            }
        }
    }
    
    html = [html stringByAppendingString:[NSString stringWithFormat:@"<style>img{width:%f !important;height:auto}body{font-size:%fpx;color:rgb(51,51,51);}</style>",kScreenW - 32,14.0f]];
    if (self.done) {
        // 获取全局并发队列
        // 获取主队列
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
            NSData *data = [html dataUsingEncoding:NSUnicodeStringEncoding];
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
            //回主线程刷新ui
            dispatch_async(dispatch_get_main_queue(), ^{
                self.done(attr);
            });
        });
    }

//    if (imageurlArray.count != 0) {
//
//    }else{
//        [self attributedTextFrom:subStrings imgSrcs:imageurlArray];
//    }
}

- (void)attributedTextFrom:(NSArray *)subStrings imgSrcs:(NSArray *)imgURLs {
    NSMutableAttributedString *string  = [[NSMutableAttributedString alloc] init];
    if (subStrings.count > 0) {
        for (int index = 0; index < subStrings.count; index++) {

            // 获取全局并发队列
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_async(queue, ^{
                NSString *subStr = subStrings[index];
                subStr = [subStr stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-size:%fpx;color:rgb(51,51,51);}</style>",14.0f]];
                
                NSAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithData:[subStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [string appendAttributedString:tmpString];
                });
            });
        
            if (imgURLs.count > index) {
                NSTextAttachment *attach = [[NSTextAttachment alloc] init];
                NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
                [string appendAttributedString:attachString];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    BOOL isChinese =  [self hasChinese:imgURLs[index]];
                    NSString *url = imgURLs[index];
                    if (isChinese) {
                        url = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
                    }
                    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                            
                    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                        if (finished) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (image) {
                                    attach.image = image;
                                    CGSize size = CGSizeMake(kScreenW - 32, image.size.height / image.size.width * (kScreenW - 32));
                                    attach.bounds = CGRectMake(0, 0, size.width, size.height);
                                    if (self.done) {
                                        self.done(string);
                                    }
                                }
                              
                            });
                        }
                        
                    }];
                });
            }
        }
    }else{
        for (NSString *url in imgURLs) {
            NSTextAttachment *attach = [[NSTextAttachment alloc] init];
            NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
            [string appendAttributedString:attachString];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                BOOL isChinese =  [self hasChinese:url];
                NSString *imgUrl = url;
                
                if (isChinese) {
                    imgUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
                }

                [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:imgUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                        
                } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                    if (finished) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (image) {
                                attach.image = image;
                                CGSize size = CGSizeMake(kScreenW - 32, image.size.height / image.size.width * (kScreenW - 32));
                                attach.bounds = CGRectMake(0, 0, size.width, size.height);
                                if (self.done) {
                                    self.done(string);
                                }
                            }
                          
                        });
                    }
                }];
            });

        }
    }
}


-(BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}


@end
